/**
 * Package     init_db
 * @author     : wgy
 * @time       : 2024/6/4 星期二 下午 17:29
 * explain     ：
**/

package init_db

import (
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
)

// InitGorm gorm初始化
func InitGorm(user, password, host, db string, port, maxIdle, maxOpen int) *gorm.DB {

	url := fmt.Sprintf(
		"%v:%v@tcp(%v:%v)/%v?charset=utf8mb4&parseTime=True&loc=Local",
		user,
		password,
		host,
		port,
		db)
	Db, err := gorm.Open(mysql.Open(url), &gorm.Config{
		//打印sql
		QueryFields:                              true,
		Logger:                                   logger.Default.LogMode(logger.Info),
		DisableForeignKeyConstraintWhenMigrating: true,
	})
	if err != nil {
		panic("连接mysql数据库失败, error=" + err.Error())
	}
	fmt.Println("连接mysql数据库成功")

	sqlDb, err := Db.DB()
	sqlDb.SetMaxIdleConns(maxIdle)
	sqlDb.SetMaxOpenConns(maxOpen)

	return Db
}
